在 Laravel 專案中,除了使用者操作可以觸發邏輯(例如發送 HTTP Request),我們也可以讓系統自動執行程式碼。
Laravel 提供了 Artisan Command 機制,讓我們可以撰寫自定義的命令來做資料處理、寄信、同步資料等工作,尤其適合搭配排程執行。
使用 Artisan 指令產生:php artisan make:command SendEmails
生成後的檔案位置為:app/Console/Commands/SendEmails.php
以下是示範範本:
namespace App\Console\Commands;
use App\Models\User; // ✅ 修正命名空間
use App\Services\DripEmailer; // ✅ 假設這是你的寄信 service
use Illuminate\Console\Command;
class SendEmails extends Command
{
/**
* Artisan 指令名稱與參數定義
*/
protected $signature = 'email:send {user} {--date=}';
/**
* 說明此指令的用途
*/
protected $description = 'Send drip emails to a specific user';
/**
* Email service 注入
*/
protected DripEmailer $drip;
public function __construct(DripEmailer $drip)
{
parent::__construct();
$this->drip = $drip;
}
/**
* 執行指令
*/
public function handle()
{
$email = $this->argument('user');
$date = $this->option('date') ?? now()->toDateString();
$user = User::where('email', $email)->first();
if (! $user) {
$this->error("User not found: $email");
return;
}
$this->info("Sending email to {$user->email} for date {$date}");
$this->drip->send($user, $date);
}
}
透過 CLI 執行:php artisan email:send test@mail.com --date=2025-01-01
若要定期執行這支指令,可在 app/Console/Kernel.php 中設定:
use Illuminate\Console\Scheduling\Schedule;
protected function schedule(Schedule $schedule): void
{
// 記得這裡不能帶參數變數,要直接寫好
$schedule->command('email:send test@mail.com --date=' . now()->toDateString())->daily();
}